package com.flowable.project.common;


import com.alibaba.fastjson.JSONObject;
import com.flowable.project.model.OpenApiInfo;
import com.flowable.project.model.ParamsInfo;

import com.flowable.project.util.JsonData;

import com.flowable.project.util.JsonUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * @Auther: admin
 * @Date: 2021/11/18 09:17
 * @Description:
 */
public class SendHttp  {

    /**
         * @Author zjl
         * @Description GET拼接路由
         * @Date 10:29 2021/11/18
         * @Param [data, openApiInfo]
         * @return com.flowable.project.util.JsonData
         **/


    public static JsonData sendGet(Map<String,String> data, OpenApiInfo openApiInfo){
        String preUrl = openApiInfo.getPathUrl();
        List<ParamsInfo> params = openApiInfo.getParams();
        String para = "?";
        if(params.size()>0){
            for(ParamsInfo p:params){
                if (p.getIsRequire()==1) {
                    if(!data.containsKey(p.getName())) {
                        return JsonData.buildError("缺少对应的参数",ErrorCode.REQUEST_PARAM_ERROR);
                    }else {
                        para += p.getName() + "=" + data.get(p.getName());
                        para += "&";
                    }
                } else{
                    if (data.containsKey(p.getName())) {
                        para += p.getName() + "=" + data.get(p.getName());
                        para += "&";
                    }
                }
            }
        }
        String s =sendRequest(data,preUrl+para,"GET");
        return JsonData.buildSuccess(s);
    }

    /**
         * @Author zjl
         * @Description POST拼接路由
         * @Date 10:30 2021/11/18
         * @Param [data, openApiInfo]
         * @return com.flowable.project.util.JsonData
         **/

    public static JsonData sendPost(Map<String,String> data, OpenApiInfo openApiInfo){
        String preUrl = openApiInfo.getPathUrl();
        List<ParamsInfo> params = openApiInfo.getParams();
        String para = "?";
        if(params.size()>0){
            for(ParamsInfo p:params){
                if (p.getIsRequire()==1) {
                    if (p.getIsBody() == 0){
                        if(!data.containsKey(p.getName())) {
                            return JsonData.buildError("缺少对应的参数",ErrorCode.REQUEST_PARAM_ERROR);
                        }else {
                            para += p.getName() + "=" + data.get(p.getName());
                            para += "&";
                            data.remove(p.getName());
                        }
                    }
                } else{
                    if (data.containsKey(p.getName()) && p.getIsBody() == 0) {
                        para += p.getName() + "=" + data.get(p.getName());
                        para += "&";
                        data.remove(p.getName());
                    }
                }
            }
        }
        String s =sendRequest(data,preUrl+para,"POST");
        return JsonData.buildSuccess(s);
    }

    //java发送http请求
    public static String sendRequest(Map<String,String> data,String urlParam,String requestType) {
        if ("GET".equals(requestType)) {
            // 创建httpClient实例对象
            HttpClient httpClient = new HttpClient();
            // 设置httpClient连接主机服务器超时时间：15000毫秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
            // 创建请求方法实例对象
            GetMethod method = new GetMethod(urlParam);
            // 设置post请求超时时间
            method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
            method.addRequestHeader("Content-Type", "application/json");
            String result = null;
            try {
                httpClient.executeMethod(method);
                result = method.getResponseBodyAsString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            method.releaseConnection();
            return result;
        } else if ("POST".equals(requestType)) {
            PostMethod method = new PostMethod(urlParam);
            try {
                //创建连接
                URL url = new URL(urlParam);
                HttpURLConnection connection = (HttpURLConnection) url
                        .openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
                connection.setRequestProperty("Content-Type",
                        "application/json");
                connection.connect();

                //POST请求
                DataOutputStream out = new DataOutputStream(
                        connection.getOutputStream());
                out.writeBytes(JsonUtil.objectToJson(data));
                out.flush();
                out.close();
                //读取响应
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String lines;
                StringBuffer sb = new StringBuffer("");
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    sb.append(lines);
                }
                reader.close();
                // 断开连接
                connection.disconnect();
                return sb.toString();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}
